import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.PrintWriter;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class InputWindow extends JFrame {
   
   private String name;
   
   private PrintWriter out;
   /**
    * Version ID.
    */
   private static final long serialVersionUID = 1L;
   /**
    * Input field for url.
    */
   public JTextField textField;
   /**
    * Constructor.
    */
   public InputWindow(final String name, final PrintWriter out) {
      this.name = name;
      this.out = out;
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);
      setTitle("Javatar - " + name);
      setSize(500, 60);
      setLocation(150, 150);
      JPanel panel = new JPanel();
      add(panel);
      panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
      textField = new JTextField();
      panel.add(textField);
      JButton button = new JButton("Send");
      panel.add(button);
      setVisible(true);
      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
           int key = e.getKeyCode();
           if (key == KeyEvent.VK_ENTER) {  
              sendMsg(textField.getText());
           }
         }
      });

      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent arg0) {
            sendMsg(textField.getText());
         }
      });
   }
   
   private void sendMsg(String msg) {
      if (msg.length() > 0) {
         out.println(msg);
         textField.setText("");
      }
   }
}
